<?php

namespace App\Http\Controllers\Users;
use App\Http\Controllers\Controller;
use App\Models\AgentApply;
use App\Models\AlimamaOrder;
use App\Models\OrderCommission;
use App\Models\PidOrder;
use App\Models\Product;
use App\Models\TaokeWithdrawCash;
use App\Models\User;
use App\Models\UserPid;
use Illuminate\Http\Request;

class TaokeAgentController extends Controller {

    public function getUserInfo(){
        global $g_uid;
        $userInfo = User::select(
            'id',
            'father_id',
            'mobile',
            'withdraw_account',
            'nick_name',
            'balance',
            'commission',
            'headimgurl'
        )->where('id', $g_uid)
            ->first();
        if(!$userInfo){
            return response()->json(['error' => '没有此用户']);
        }

        $userInfo->balance = round($userInfo->balance, 2);
        $userInfo->commission = round($userInfo->commission, 2);
        return response()->json($userInfo);
    }

    public function fatherUser(Request $request){
        global $g_uid;
        $isAgent = null;
        if($request->has('agent')){
            $isAgent = $request->get('agent');
        }

        $usersql = User::select(
                'id',
                'father_id',
                'mobile',
                'nick_name',
                'balance',
                'commission',
                'headimgurl',
                'created_at'
            )->where('father_id', $g_uid);
        if($isAgent !== null){
            $usersql->where('is_agent', $isAgent);
        }

        $userList = $usersql->get()->toArray();
        foreach ($userList as &$user){
            $user['created_at'] = date('Y年m月d日', strtotime($user['created_at']));
        }
        $userCount = $usersql->count();
        $todayCount = $usersql->where('created_at', '>=', date('Y-m-d', time()))->count();

        return response()->json(['list' => $userList, 'userCount' => $userCount, 'todayCount' => $todayCount]);
    }

    public function getOrder(Request $request){
        global $g_uid;

        $orderModel = new AlimamaOrder();
        $userPidModel = new UserPid();
        $userModel = new User();
        $pidOrder = new PidOrder();
        $goodsModel = new Product();
        $orderCommissionModel = new OrderCommission();

        $sql = \DB::table($userModel->getTable() . ' as u')
            ->select(
                'o.*',
                'up.user_id',
                'oc.commission1',
                'oc.commission2',
                \DB::raw('round(commission1/paid_amount*100, 2) as commission1_rate'),
                \DB::raw('round(commission2/paid_amount*100, 2) as commission2_rate'),
                'g.goods_pic',
                'g.goods_name',
                \DB::raw("if(user_id != {$g_uid}, 1,0) as agent")
            )
            ->leftJoin($userPidModel->getTable() . ' as up', 'u.id', '=', 'up.user_id')
            ->leftJoin($pidOrder->getTable() .' as po', 'po.pid_id', '=', 'up.pid_id')
            ->leftJoin($orderCommissionModel->getTable() . ' as oc', 'oc.order_id', '=', 'po.order_id')
            ->leftJoin($orderModel->getTable() .' as o', 'o.id', '=', 'po.order_id')
            ->leftJoin($goodsModel->getTable(). ' as g', 'g.tbid', '=', 'o.tbid')
            ->whereNotNull('o.id')
            ->where('u.is_agent', 1);

        $type = null;
        if($request->has('type')){
            $type = $request->get('type');
        }

        if($type == 'my'){
            $sql->where('u.id', $g_uid);
        }elseif($type == 'agent'){
            $sql->where('u.father_id', $g_uid);
        }else{
            $sql->where(function ($query) use($g_uid){
                $query->where('u.id', $g_uid)->orWhere('u.father_id', $g_uid);
            });
        }

        $page = $request->get('page', 1);
        $length = $request->get('pageSize', 20);
        $offset = ($page - 1) * $length;

        $count = $sql->count();
        $orderData = $sql->orderBy('o.create_time', 'desc')
            ->skip($offset)->take($length)
            ->get();
        return response()->json(['list' => $orderData,'count' => $count]);
    }

    public function agentApply(Request $request){
        global $g_uid;
        $params = ['mobile', 'wechat', 'code'];
        foreach ($params as $param){
            if(!$request->get($param)){
                return response()->json(['error' => "{$param}必须填写"]);
            }
        }

        $code = $request->get('code');
        $mobile = str_replace(' ', '', trim($request->get('mobile')));
        $cacheCode = \Cache::get($mobile);
        \Log::debug($cacheCode);
        if($code != $cacheCode){
            return response()->json(['error' => "验证码不正确"]);
        }

        $saveData = [
            'mobile' => $mobile,
            'wechat' => $request->get('wechat'),
            'uid' => $g_uid,
            'created_at' => date('Y-m-d H:i:s', time())
        ];

        if(AgentApply::create($saveData)){
            return response()->json('success');
        }else{
            return response()->json(['error' => "申请失败"]);
        }
    }

    public function withdraw(Request $request){
        global $g_uid;
        $amount = $request->get('amount', 0);
        if($amount < 100){
            return response()->json(['error' => '提现金额不能少于100']);
        }

        $userInfo = User::where('id', $g_uid)->first();
        if(!$userInfo){
            return response()->json(['error' => '用户信息错误']);
        }

        if($amount > $userInfo->balance){
            return response()->json(['error' => '可提现金额不足']);
        }

        if(TaokeWithdrawCash::where('uid', $g_uid)->where('status', 1)->count()){
            return response()->json(['error' => '上一笔提现还未完成']);
        }

        if(TaokeWithdrawCash::create([
            'uid' => $g_uid,
            'amount' => $amount,
            'created_at' => date('Y-m-d H:i:s', time())
        ])){
            return response()->json('申请成功');
        }else{
            return response()->json(['error' => '申请失败']);
        }
    }
}
